import {
  login,
  loginSms,
  getArea,
  logout,
  getUserInfo,
  // getMessage,
  // getContentByMsgId,
  // hasRead,
  removeReaded,
  restoreTrash
  // getUnreadCount
} from '@/api/user'
import Cookies from 'js-cookie'
import { setToken, getToken, get_user_info, set_user_info, remove_user_info, getShowKaptcha, remove_all_cookie } from '@/libs/util.js'
import qs from 'qs'
// import VueCookie from 'vue-cookie';
// "indent": ["off", 2];
export default {
  state: {
    userName: '',
    userId: '',
    avatarImgPath: '',
    token: getToken(),
    user: get_user_info(),
    showKaptcha: getShowKaptcha(),
    access: '',
    hasGetInfo: false,
    unreadCount: 0
    // messageUnreadList: [],
    // messageReadedList: [],
    // messageTrashList: [],
    // messageContentStore: {}
  },
  mutations: {
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_USER_AVATAR: (state, avatar) => {
      state.user.imgUrl = avatar
    },
    SET_KAPTCHA: (state, show) => {
      state.showKaptcha = show
    },
    setAvatar (state, avatarPath) {
      state.user.imgUrl = avatarPath
    },
    // setUserId (state, id) {
    //   state.userId = id
    // },
    // setUserName (state, name) {
    //   state.userName = name
    // },
    setAccess (state, access) {
      state.access = access
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    token: state => {
      return state.token
    },
    user: state => {
      return state.user
    }
    // messageUnreadCount: state => state.messageUnreadList.length,
    // messageReadedCount: state => state.messageReadedList.length,
    // messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    store_showKaptcha ({ commit }, show) {
      Cookies.set('showKaptcha', show)
      commit('SET_KAPTCHA', show)
    },
    // 登录，异步请求token,将token作为共享数据
    handleLogin ({ commit }, userinfo) {
      return new Promise((resolve, reject) => {
        login(qs.stringify(userinfo)).then(res => {
          const data = res.data
          if (data.code !== 0) {
            resolve(data)
          } else {
            
            commit('setToken', data.data)
            commit('setTagNavList', [])
            resolve(data)
          }

          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 验证码登录
    handleLoginSms ({ commit }, userinfo) {
      return new Promise((resolve, reject) => {
        loginSms(userinfo).then(res => {
          const data = res.data
          if (data.code !== 0) {
            resolve(data)
          } else {
            commit('setToken', data.data)
            commit('setTagNavList', [])
            resolve(data)
          }

          resolve(data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setAccess', [])
          var myDate = new Date()
          myDate.setTime(-1000)// 设置时间
          document.cookie = "area=''; expires=" + myDate.toGMTString()
          console.log(document.cookie,'document.cookie')
          remove_all_cookie()
          resolve()
        }).catch(err => {
          reject(err)
        })
        // 如果你的退出登录无需请求接口，则可以直接使用下面三行代码而无需使用logout调用接口
        // commit('setToken', '')
        // commit('setAccess', [])
        // resolve()
      })
    },
    // 获取地区权限
    async handleArea ({ state, commit }) {
      console.log('获取地区权限')
      let result = (await getArea(state.token))
      if (result.status == 200) {
        let res = result.data.data
        console.log(123, res)
        for (var i = 0; i < res.length; i++) {
          res[i] == null || res[i] == '' ? res[i] = '' : ''
        }
        res[6] == '' ? res[6] = 1 : ''
        document.cookie = 'area=' + res
        console.log('run is success!', state.nowArea)
      } else {
        console.log(result)
        this.$Message.error(data.message)
      }
    },
    // 设置头像
    store_set_avatar ({ commit }, avatar) {
      commit('setAvatar', avatar)
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo(state.token).then(response => {
            if (response.data.code === 0) {
              const data = response.data.data
              // 设置权限列表
              let permissionList = []
              function p (menus) {
                if (typeof menus === 'object') {
                  menus.forEach((ele, index) => {
                    permissionList.push(ele.code)
                    if (ele.children.length) {
                      p(ele.children)
                    }
                  })
                }
              }
              p(data.menus)
              data.permissionList = permissionList
              commit('setAccess', permissionList)
              commit('SET_USER', data)
              commit('setAvatar', data.imgUrl)
              set_user_info(data)
              resolve(data)
            } else {
              Message.error(response.message)
              reject(response.message)
            }
            const data = response.data
            // commit('setAvatar', data.avatar)
            // commit('setUserName', data.name)
            // commit('setUserId', data.user_id)
            // commit('setAccess', data.access)
            commit('setHasGetInfo', true)
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    }
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    // getUnreadMessageCount ({ state, commit }) {
    //   getUnreadCount().then(res => {
    //     const { data } = res
    //     commit('setMessageCount', data)
    //   })
    // },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    // getMessageList ({ state, commit }) {
    //   return new Promise((resolve, reject) => {
    //     getMessage().then(res => {
    //       const { unread, readed, trash } = res.data
    //       commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageReadedList', readed.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       commit('setMessageTrashList', trash.map(_ => {
    //         _.loading = false
    //         return _
    //       }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // 根据当前点击的消息的id获取内容
    // getContentByMsgId ({ state, commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     let contentItem = state.messageContentStore[msg_id]
    //     if (contentItem) {
    //       resolve(contentItem)
    //     } else {
    //       getContentByMsgId(msg_id).then(res => {
    //         const content = res.data
    //         commit('updateMessageContentStore', { msg_id, content })
    //         resolve(content)
    //       })
    //     }
    //   })
    // },
    // 把一个未读消息标记为已读
    // hasRead ({ state, commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     hasRead(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageUnreadList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       commit('setMessageCount', state.unreadCount - 1)
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 删除一个已读消息到回收站
    // removeReaded ({ commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     removeReaded(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageReadedList',
    //         to: 'messageTrashList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    // // 还原一个已删除消息到已读消息
    // restoreTrash ({ commit }, { msg_id }) {
    //   return new Promise((resolve, reject) => {
    //     restoreTrash(msg_id).then(() => {
    //       commit('moveMsg', {
    //         from: 'messageTrashList',
    //         to: 'messageReadedList',
    //         msg_id
    //       })
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // }
  }
}
